package springboot.study.project.aop;

import springboot.study.project.annotation.LogRecord;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName: LogRecordAspect
 * @Description: 日志记录Aop
 * @Author: liu-hao
 * @Date: 2021-02-18 15:51
 * @Version: 1.0
 **/
@Aspect
@Component
@Order(2)
// @ConditionalOnProperty(prefix = "spring.log.detail", name = "enable", havingValue = "true") // 配置文件决定是否初始化：spring.log.detail.enable=true
public class LogRecordAspect {

    // 扫描自定义注解
    @Pointcut("@annotation(springboot.study.project.annotation.LogRecord)")
    public void webLog() {
    }

    @Around(value = "webLog()")
    public void doAround(ProceedingJoinPoint point) {
        System.out.println("...进入Aop方法");


        Map<String, Object> map = null;
        try {
            map = getLog(point);
        } catch (Throwable throwable) {
            map = new HashMap<>();
            throwable.printStackTrace();
        }

        System.out.println(map.toString());
    }

    private Map<String, Object> getLog(ProceedingJoinPoint joinPoint) throws Throwable {
        Map<String, Object> resultMap = new HashMap<>();

        //先查找类上的注解，没有再找方法上的注解
        LogRecord clazzLogRecord = joinPoint.getTarget().getClass().getAnnotation(LogRecord.class);
        LogRecord methodLogRecord = null;
        Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
        methodLogRecord = method.getAnnotation(LogRecord.class);


        String system = "";
        String module = "";
        String menuLv1 = "";
        String menuLv2 = "";
        // 1. 获取请求信息
        if (clazzLogRecord != null) {
            system = clazzLogRecord.system();
            module = clazzLogRecord.module();
        }
        if (methodLogRecord != null) {
            menuLv1 = methodLogRecord.menuLv1();
            menuLv2 = methodLogRecord.menuLv2();
        }
        resultMap.put("log", system + "-" + module + "-" + menuLv1 + "-" + menuLv2);
        // 2. 获取请求参数
        Object[] args = joinPoint.getArgs();
        for (int i = 0; i < args.length; i++) {
            resultMap.put("输入参数-" + (i + 1), args[i]);
        }
        // 3. 获取请求结果
        Object result = joinPoint.proceed(); // 请求结果
        resultMap.put("输出参数", result);

        return resultMap;
    }
}
